package database;

import java.util.Iterator;
import java.util.NoSuchElementException;


public class OrderedLinkedList <K extends Comparable<K>, V> implements Dictionary <K, V>   {
	
	//Constructors and Instance Variables
	private OrderedLinkedListEntry<K, V> node;
	private int size;
	
	//Methods
	
	//Clear Method
	public void clear() {
		node = null;
		
	}
	
	//Method for getting a value given a key
	public V get(K key) throws NoSuchElementException {
		
		while (iterator().hasNext()) {
			if (node.getKey().equals(key)) {
				return node.getValue();
			}
			iterator().next();
		}
		throw new NoSuchElementException();
	}

	public boolean isEmpty() {
		if (node == null) {
			return true;
		}
		else {
			return false;
		}
	}

	public void put(K key, V value) {
		
		while (iterator().hasNext()){
		//Making a new node if the list is empty
		
			if (node == null){
			node = new OrderedLinkedListEntry(key, value);
			size++;
			return;
		}
		
			else {
			//If the node is equal then update the entry
				if (node.getKey().compareTo(key) == 0){
				node.setValue(value);
				return;
				}
				else {
				//If the next node is greater than the new one
					if (node.getNext().getKey().compareTo(key) == 1) {
					insert(key, value);					
					}
					else{
					iterator().next();
					}	
				}
			}	
		}	
	}
	
	private void insert(K ikey, V ival){
		OrderedLinkedListEntry<K, V>inode = new OrderedLinkedListEntry<K, V>(ikey, ival);
		inode.setNext(node.getNext());
		node.setNext(inode);
			
	}

	public void remove(K key) throws NoSuchElementException {
		if (node.getKey().equals(key)){
			node = node.getNext(); 
			return;
		}
		
		while (iterator().hasNext()){
			if (node.getNext().getKey().equals(key)) {
				node.setNext(node.getNext().getNext());
			}
			iterator().next();
		}
		throw new NoSuchElementException();
		
	}

	public int size() {
		return size;
	}

	public Iterator<DictionaryEntry<K, V>> iterator() {
			return new ListIterator();
	}
	
	
	//Implentation of the List Iterator
	private class ListIterator implements Iterator<DictionaryEntry<K, V>> {

		public boolean hasNext() {
			if (node.getNext() != null) {
				return true;
			}
			else {
				return false;
			}
		}

		public DictionaryEntry<K, V> next() {
			OrderedLinkedListEntry<K, V> result = node;
			node = node.getNext();
			return result;
		}

		public void remove() {
			
		}
		
	}

		
	}
	

